
package cz.czu.pef.DataModelling;

import java.util.*;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.*;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cz.czu.pef.DataModelling.utils.Lazy;

@Entity
@Table(name = "EXTERNAL_WORKERS")
@Inheritance(strategy = InheritanceType.JOINED)
//@DiscriminatorValue("EMPLOYEE")
@ManagedBean
@ViewScoped
@Component
public class ExternalWorker extends Employee
{
	private static final long serialVersionUID = -9003701092553813511L;

	@ManyToMany(fetch = FetchType.LAZY, targetEntity = Company.class, mappedBy = "extWorkers") // no cascade!
	private Set<Company> externalEmployers;

	public ExternalWorker()
	{
	}

	public ExternalWorker(Person person)
	{
		super(person);
	}

	public void addExternalEmployer(Company newEmployer)
	{
		if (externalEmployers == null)
			externalEmployers = new HashSet<Company>();
		externalEmployers.add(newEmployer);
	}


	@Lazy
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public Set<Company> getExternalEmployers()
	{
		return externalEmployers;
	}

	@Lazy
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	@Override
	public String toString()
	{
		StringBuilder builder = new StringBuilder();
		builder.append("ExternalWorker [toString()=");
		builder.append(super.toString());
		builder.append("]");
		return builder.toString();
	}
	
	/**
	 * Can be deleted after no employer is referencing it.
	 */
	@Override
	public boolean canBeRemoved()
	{
		return getExternalEmployers().size() == 0 && super.canBeRemoved();
	}
}